package gameModel;

import gameModel.Case.CaseStates;

public class StdGridModel implements GridModel {
	
	// ATTRIBUTS
	
	private final Case[][] grid;
	
	// CONSTRUCTEUR
	
	public StdGridModel(int width, int height) {
		if (width < MIN_WIDTH || width > MAX_WIDTH
				|| height < MIN_HEIGHT || height > MAX_HEIGHT) {
			throw new IllegalArgumentException();
		}
		grid = new Case[width][height];
		for (int i = 0; i < width; i++) {
			for (int j = 0; j < height; j++) {
				grid[i][j] = new StdCase(Case.CaseStates.getDefaultState());
			}
		}
	}
	
	// REQUETES

	@Override
	public CaseStates getCaseState(Coord c) {
		if (c.x < 0 || c.x >= getWidth()
				|| c.y < 0 || c.y >= getHeight()
				|| grid[c.x][c.y] == null) {
			return null;
		}
		return grid[c.x][c.y].getCaseState();
	}

	@Override
	public int getWidth() {
		return grid.length;
	}

	@Override
	public int getHeight() {
		return grid[0].length;
	}

	@Override
	public Piece getPiece(Coord c) {
		if (c.x < 0 || c.x >= getWidth()
				|| c.y < 0 || c.y >= getHeight()
				||grid[c.x][c.y] == null) {
			return null;
		}
		return grid[c.x][c.y].getPiece();
	}
	
	@Override
	public String toString() {
		StringBuffer s = new StringBuffer();
		for (int i = 0; i < getWidth(); i++) {
			s.append(" ---");
		}
		s.append("\n");
		for (int j = 0; j < getHeight(); j++) {
			s.append("|");
			for (int i = 0; i < getWidth(); i++) {
				s.append(" ");
				if (grid[i][j] == null) {
					s.append("X");
				} else if (grid[i][j].getPiece() != null) {
					s.append(grid[i][j].getPiece());
				} else {
					s.append(grid[i][j].getCaseState().getId());
				}
				s.append(" |");
			}
			s.append("\n");
			for (int i = 0; i < getWidth(); i++) {
				s.append(" ---");
			}
			s.append("\n");
		}
		return s.toString();
	}
	
	// COMMANDES

	@Override
	public void setCaseState(Coord c, CaseStates state) {
		if (state == null) {
			grid[c.x][c.y] = null; 
		} else if (grid[c.x][c.y] == null) {
			grid[c.x][c.y] = new StdCase(state);
		} else {
			grid[c.x][c.y].setCaseState(state);
		}
	}

	@Override
	public void placePiece(Coord c, Piece p) {
		CaseStates s = getCaseState(c);
		if (p == null || s == null || !s.isWalkable() || getPiece(c) != null) {
			throw new IllegalArgumentException("p = " + p + " ; s = " + s);
		}
		grid[c.x][c.y].setPiece(p);
	}

	@Override
	public void removePiece(Coord c) {
		grid[c.x][c.y].setPiece(null);
	}

}
